package gdufs.lkl.calculator;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ExchangeRateService {
    private static final String API_KEY = "6ed467f49af4a3a8f817dc21";
    private static final String BASE_URL = "https://v6.exchangerate-api.com/";
    private static final String PREF_NAME = "exchange_rates";
    private static final String PREF_RATES = "rates";
    private static final String PREF_LAST_UPDATE = "last_update";
    private static final long UPDATE_INTERVAL = 24 * 60 * 60 * 1000; // 24小时更新一次

    private static ExchangeRateService instance;
    private final ExchangeRateApiService apiService;
    private final SharedPreferences preferences;
    private final Gson gson = new Gson();
    
    // 货币代码映射表
    private final Map<String, String> currencyCodeMap = new HashMap<String, String>() {{
        put("人民币", "CNY");
        put("美元", "USD");
        put("欧元", "EUR");
        put("英镑", "GBP");
        put("日元", "JPY");
        put("韩元", "KRW");
        put("港币", "HKD");
    }};

    private ExchangeRateService(Context context) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        
        apiService = retrofit.create(ExchangeRateApiService.class);
        preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }

    public static synchronized ExchangeRateService getInstance(Context context) {
        if (instance == null) {
            instance = new ExchangeRateService(context.getApplicationContext());
        }
        return instance;
    }

    public void updateRatesIfNeeded(RatesCallback callback) {
        long lastUpdate = preferences.getLong(PREF_LAST_UPDATE, 0);
        if (System.currentTimeMillis() - lastUpdate > UPDATE_INTERVAL) {
            fetchLatestRates(callback);
        } else {
            Map<String, Double> rates = getCachedRates();
            if (rates != null && !rates.isEmpty()) {
                callback.onRatesUpdated(rates);
            } else {
                fetchLatestRates(callback);
            }
        }
    }

    private void fetchLatestRates(RatesCallback callback) {
        Call<ExchangeRateResponse> call = apiService.getLatestRates(API_KEY, "USD");
        
        call.enqueue(new Callback<ExchangeRateResponse>() {
            @Override
            public void onResponse(Call<ExchangeRateResponse> call, Response<ExchangeRateResponse> response) {
                if (response.isSuccessful() && response.body() != null && "success".equals(response.body().result)) {
                    Map<String, Double> rates = response.body().conversion_rates;
                    cacheRates(rates);
                    callback.onRatesUpdated(rates);
                } else {
                    Map<String, Double> cachedRates = getCachedRates();
                    if (cachedRates != null && !cachedRates.isEmpty()) {
                        callback.onRatesUpdated(cachedRates);
                    } else {
                        callback.onError("获取汇率失败");
                    }
                }
            }

            @Override
            public void onFailure(Call<ExchangeRateResponse> call, Throwable t) {
                Map<String, Double> cachedRates = getCachedRates();
                if (cachedRates != null && !cachedRates.isEmpty()) {
                    callback.onRatesUpdated(cachedRates);
                } else {
                    callback.onError("网络错误: " + t.getMessage());
                }
            }
        });
    }

    private void cacheRates(Map<String, Double> rates) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(PREF_RATES, gson.toJson(rates));
        editor.putLong(PREF_LAST_UPDATE, System.currentTimeMillis());
        editor.apply();
    }

    private Map<String, Double> getCachedRates() {
        String ratesJson = preferences.getString(PREF_RATES, null);
        if (ratesJson != null) {
            Type type = new TypeToken<Map<String, Double>>() {}.getType();
            return gson.fromJson(ratesJson, type);
        }
        return null;
    }

    public String getCodeFromName(String currencyName) {
        return currencyCodeMap.getOrDefault(currencyName, "USD");
    }

    public interface RatesCallback {
        void onRatesUpdated(Map<String, Double> rates);
        void onError(String errorMessage);
    }
}
